<template>
  <div class="middle">
    <div class="page-main">
      <div class="middle-header">
        <h5>{{ CATEGORY_MAP[postStore.category] || '全部帖子' }}</h5>
        <div class="filter-buttons">
          <button
            v-for="(btn, index) in buttons"
            :key="index"
            class="filter-btn"
            :class="{ active: activeIndex === index }"
            @click="setActive(index)"
          >
            {{ btn }}
          </button>
        </div>
      </div>

      <div class="middle-content">
        <div
          class="post"
          v-for="(post, index) in posts"
          :key="post.id"
          @click="ToDetail(post.id)"
        >
          <!-- 添加flex容器包裹内容和图片 -->
          <div class="post-container">
            <!-- 文本区域 -->
            <div class="post-text">
              <h3 class="post-title">{{ post.title }}</h3>
              <div class="post-content">
                <p v-html="post.content" />
              </div>
              <div class="post-bottom">
                <span class="publish-time">发布于 {{ dayjs(post.createTime).format("YYYY-MM-DD HH:MM") }}</span>
                <span
                  class="like-count"
                  :class="{ active: post.isLike }"
                  @click.stop="toggleLike(index, post.id)"
                >
                  <i :class="post.isLiked ? 'fas fa-thumbs-up' : 'far fa-thumbs-up'"></i>
                  {{ post.liked }}
                </span>
                <!-- :class="{ active: post.isLiked }"  true的时候添加active类 false的时候移除 -->
                <span>
                  <i class="far fa-comment"></i>
                  {{ post.comments }}
                </span>

              </div>
              <div class="post-tag-row">
                <span class="post-tag">{{ CATEGORY_MAP[post.category] }}</span>
              </div>
            </div>
            <!-- 图片区域 -->
              <div class="post-image">
                <img v-if="post.images" :src="post.images" />
              </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import {getHotPostAPI, getNewPostAPI, toggleLikeAPI} from "@/api/post.js";
import dayjs from "dayjs";
import {usePostStore} from "@/stores/postStore.js";
import {ElMessage} from "element-plus";

const router = useRouter();
const buttons = ref(["最新", "热门"]);
const activeIndex = ref(0); // 默认选中"最新"
const posts = ref([]);
// 请求参数
const queryData = ref({
  current: 1, // 页数
});
const isLoading = ref(false); // 用于防止重复请求
const CATEGORY_MAP = ref(['学习', '生活', '社交', '职业'])
const postStore = usePostStore()

watch(() => postStore.category, () => {
  getPostList()
})
// 获取帖子列表
const getPostList = async () => {
  try {
    if (isLoading.value) return; // 如果正在加载，则直接返回
    isLoading.value = true; // 开始加载

    let res = null // 接收返回的数据
    if (activeIndex.value === 0) {
      res = await getNewPostAPI({
        ...queryData.value,
        category: postStore.category
      }) // 获取最新帖子
    } else {
      res = await getHotPostAPI({
        ...queryData.value,
        category: postStore.category
      }) // 获取最热帖子
    }

    if (res.code != 200) return

    // 判断是否还有数据
    if (res.data.length === 0) {
      window.removeEventListener('scroll', handleScroll);
    }

    posts.value = queryData.value.current === 1 ? res.data : [...posts.value, ...res.data]; // 数据拼接
    isLoading.value = false; // 加载结束
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
};

const handleScroll = () => {
  const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
  if (scrollTop + clientHeight >= scrollHeight - 120) { // 距离底部120px时触发
    queryData.value.current++;
    getPostList();
  }
};

onMounted(() => {
  getPostList();
  window.addEventListener('scroll', handleScroll); // 开启监听
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll); // 停止监听
});

const setActive = (index) => {
  activeIndex.value = index;
  queryData.value.current = 1; // 切换筛选条件时重置为第一页
  posts.value = []; // 清空原有数据
  window.addEventListener('scroll', handleScroll); // 重启对滚动的监听
  getPostList();
};

const ToDetail = (id) => {
  router.push(`/detail?id=${id}`);
};

// 切换点赞
const toggleLike = (index, id) => {
  const post = posts.value[index];
  post.isLike = !post.isLike;
  post.liked += post.isLike ? 1 : -1;

  toggleLikeAPI(id)
};
</script>

<style scoped>
/* 中间部分 */
.middle {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px 0;
  /* background-color: lightblue; */
}

.page-main {
  width: 100%;
  /* background-color: greenyellow; */
  margin: 0 auto;
  padding: 0px 20px;
  border-radius: 8px;
}

/* 标题和筛选按钮区域 */
.middle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  /* background-color: yellow; */
}

.middle-header h5 {
  font-size: 25px;
  font-weight: bold;
  color: #333;
}

.filter-buttons {
  display: flex;
  gap: 8px;
  /* 按钮间距 */
}

.filter-btn {
  padding: 6px 12px;
  background: none;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
  font-size: 16px;
  transition: all 0.3s;
}

.filter-btn:hover {
  /* color: #1890ff; */
  background-color: #e9ecef;
}

.filter-btn.active {
  color: #1890ff;
  background: #e6f7ff;
}

.middle-content {
  padding: 20px;
  background: white;
}

/* 帖子部分 */
.post {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.post:last-child {
  border-bottom: none;
}

.post-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  cursor: pointer;
}
.post-container:hover .post-title {
  color: #1890ff;
}

.post-text {
  flex: 1;
}

.post-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 12px;
  font-weight: bold;
}

.post-content {
  font-size: 15px;
  color: #555;
  margin-bottom: 15px;
}

.post-content p {
  margin-bottom: 15px;
}

.post-bottom {
  font-size: 13px;
  color: gray;
}

.post-bottom span {
  margin-right: 15px;
}

.post-bottom span:last-child {
  margin-right: 0;
}


.post-image {
  width: 150px;
  height: 100px;
  overflow: hidden;
  border-radius: 4px;
}

.post-image img {
  width: 100%;
  height: 100%;
}
.post-tag-row {
  margin-top: 10px;
}

.post-tag {
  display: inline-block;
  padding: 3px 8px;
  background: #f5f5f5; /* 浅灰色背景 */
  color: #666; /* 深灰色文字 */
  border-radius: 4px;
  font-size: 12px;
  border: 1px solid #e0e0e0; /* 更浅的边框 */
}

.post-bottom span {
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
/* 新增图标样式 */
.post-bottom i {
  margin-right: 4px;
  font-size: 14px;
}


/* 点赞激活状态 */
.like-count.active {
  color: #1890ff;
}

/* 统一交互效果 */
.like-count {
  cursor: pointer;
  transition: color 0.3s;
}
</style>
